package com.getpebble.android.onboarding.fragment;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.core.util.PblPreferences.PrefKey;
import com.getpebble.android.common.framework.fragment.PblBaseFragment;
import com.getpebble.android.connection.ConnectionManagerFragment;
import com.getpebble.android.core.auth.activity.LoginActivity;
import com.getpebble.android.onboarding.activity.OnboardingActivity;

public class PebbleOnlyFragment extends PblBaseFragment {
    private Button mButton;
    private TextView mModelDescription;
    private TextView mModelName;
    private ViewPager mSelector;

    private enum PebbleModel {
        TINTIN(R.drawable.device_pebble_original_black, R.string.model_pebble, true),
        BIANCA(R.drawable.device_pebble_steel_light, R.string.model_pebble_steel, true),
        SNOWY(R.drawable.device_pebble_time_red, R.string.model_pebble_time, false),
        BOBBY(R.drawable.device_pebble_timesteel_light, R.string.model_pebble_time_steel, false),
        S4(R.drawable.device_pebble_round_white14mm, R.string.model_pebble_time_round, false);
        
        private final int mImage;
        private final int mName;
        private final boolean mSupported;

        private PebbleModel(int image, int name, boolean supported) {
            this.mImage = image;
            this.mName = name;
            this.mSupported = supported;
        }

        public int getImage() {
            return this.mImage;
        }

        public int getName() {
            return this.mName;
        }

        public boolean isSupported() {
            return this.mSupported;
        }
    }

    private class PebblePagerAdapter extends PagerAdapter {
        private PebblePagerAdapter() {
        }

        public Object instantiateItem(ViewGroup viewGroup, int position) {
            PebbleModel pebble = PebbleModel.values()[position];
            View layout = LayoutInflater.from(PebbleOnlyFragment.this.getActivity()).inflate(R.layout.fragment_only_pebble_item, viewGroup, false);
            ((ImageView) layout.findViewById(R.id.model)).setImageResource(pebble.getImage());
            viewGroup.addView(layout);
            return layout;
        }

        public void destroyItem(ViewGroup collection, int position, Object view) {
            collection.removeView((View) view);
        }

        public int getCount() {
            return PebbleModel.values().length;
        }

        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    public int getLayoutId() {
        return R.layout.fragment_only_pebble;
    }

    public void init(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Trace.debug("PebbleOnlyFragment", "Initializing PebbleOnlyFragment");
        ActionBar actionBar = getActivity().getActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        PblPreferences prefs = new PblPreferences(PebbleApplication.getAppContext());
        if (!prefs.getBooleanData(PrefKey.USER_SEEN_PEBBLE_ONLY_SCREEN, false)) {
            prefs.setBooleanData(PrefKey.USER_SEEN_PEBBLE_ONLY_SCREEN, true);
        }
        this.mModelName = (TextView) container.findViewById(R.id.model_name);
        this.mModelDescription = (TextView) container.findViewById(R.id.model_description);
        this.mButton = (Button) container.findViewById(R.id.button);
        this.mSelector = (ViewPager) container.findViewById(R.id.selector);
        this.mSelector.setPageMargin(-getResources().getDimensionPixelSize(R.dimen.watch_selector_viewpager_margin));
        this.mSelector.setOffscreenPageLimit(2);
        this.mSelector.setAdapter(new PebblePagerAdapter());
        this.mSelector.addOnPageChangeListener(new OnPageChangeListener() {
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            public void onPageSelected(int position) {
                PebbleOnlyFragment.this.updateText();
            }

            public void onPageScrollStateChanged(int state) {
            }
        });
        this.mButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (PebbleModel.values()[PebbleOnlyFragment.this.mSelector.getCurrentItem()].isSupported()) {
                    PebbleOnlyFragment.this.moveToNextScreen();
                } else if (PebbleOnlyFragment.this.isTimeAppInstalled()) {
                    PebbleOnlyFragment.this.openPebbleTimeApp();
                } else {
                    ConnectionManagerFragment.goToPlayStoreForPebbleTimeApp(PebbleOnlyFragment.this.getActivity());
                }
            }
        });
    }

    private void openPebbleTimeApp() {
        Intent i = getActivity().getPackageManager().getLaunchIntentForPackage("com.getpebble.android.basalt");
        if (i == null) {
            Trace.warning("PebbleOnlyFragment", "Could not open Pebble Time app - redirecting to play store");
            ConnectionManagerFragment.goToPlayStoreForPebbleTimeApp(getActivity());
            return;
        }
        i.addCategory("android.intent.category.LAUNCHER");
        startActivity(i);
    }

    public void onResume() {
        super.onResume();
        updateText();
    }

    private void updateText() {
        int descriptionString;
        int buttonString;
        PebbleModel model = PebbleModel.values()[this.mSelector.getCurrentItem()];
        if (model.isSupported()) {
            descriptionString = R.string.works_with_this_app;
            buttonString = R.string.onbording_continue;
        } else if (isTimeAppInstalled()) {
            descriptionString = R.string.works_with_a_different_app;
            buttonString = R.string.open_app;
        } else {
            descriptionString = R.string.works_with_a_different_app_please_download_it;
            buttonString = R.string.download_app;
        }
        this.mModelName.setText(getString(model.getName()));
        this.mModelDescription.setText(getString(descriptionString, new Object[]{getString(model.getName())}));
        this.mButton.setText(buttonString);
    }

    private boolean isTimeAppInstalled() {
        return isPackageInstalled("com.getpebble.android.basalt", getActivity());
    }

    private static boolean isPackageInstalled(String packagename, Context context) {
        try {
            context.getPackageManager().getPackageInfo(packagename, 1);
            return true;
        } catch (NameNotFoundException e) {
            return false;
        }
    }

    private void moveToNextScreen() {
        Activity activity = getActivity();
        if (activity instanceof LoginActivity) {
            ((LoginActivity) activity).switchToLoginFragment();
        } else if (activity instanceof OnboardingActivity) {
            ((OnboardingActivity) activity).showCurrentScreen();
        }
        Trace.error("PebbleOnlyFragment", "activity is not a LoginActivity or OnboardingActivity! (it is a " + activity + ")");
    }
}
